package org.dez;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import com.e3roid.E3Activity;
import com.e3roid.E3Engine;
import com.e3roid.E3Scene;
import com.e3roid.drawable.modifier.AlphaModifier;
import com.e3roid.drawable.modifier.SpanModifier;
import com.e3roid.drawable.sprite.TextSprite;
import com.e3roid.drawable.tmx.TMXException;
import com.e3roid.drawable.tmx.TMXLayer;
import com.e3roid.drawable.tmx.TMXTiledMap;
import com.e3roid.drawable.tmx.TMXTiledMapLoader;
import com.e3roid.event.SceneUpdateListener;
import com.e3roid.util.Debug;

import java.util.ArrayList;

@SuppressWarnings("unchecked")
public class MainActivity extends E3Activity implements SceneUpdateListener
{
    private final static int WIDTH  = 480;
    private final static int HEIGHT = 320;

    private TMXTiledMap map;
    private ArrayList<TMXLayer> mapLayers;
    private TMXLayer collisionLayer;
    private int lastTouchX;
    private int lastTouchY;
    private int mapX;
    private int mapY;

    @Override
    public E3Engine onLoadEngine() {
        E3Engine engine = new E3Engine(this, WIDTH, HEIGHT);
        engine.requestFullScreen();
        engine.requestLandscape();
        return engine;
    }

    @Override
    public E3Scene onLoadScene() {
        final E3Scene scene = new E3Scene();
        scene.addEventListener(this);
        scene.registerUpdateListener(10, this);
        // add loading text with blink modifier
        //final TextSprite loadingText = new TextSprite("Loading map...", 24, this);
        //loadingText.move((getWidth()  - loadingText.getWidth())  / 2,
        //        (getHeight() - loadingText.getHeight()) / 2);
        //loadingText.addModifier(new SpanModifier(500L, new AlphaModifier(0, 0, 1)));
        //scene.getTopLayer().add(loadingText);

        // limit refresh rate while loading for saving cpu power
        engine.setRefreshMode(E3Engine.REFRESH_LIMITED);
        engine.setPreferredFPS(10);

        // loading maps could take some time so work in background.
        //new AsyncTask<Void,Integer,TMXTiledMap>() {
        //    @Override
        //    protected TMXTiledMap doInBackground(Void... params) {
                // get the map from TMX map file.
                try {
                    TMXTiledMapLoader mapLoader = new TMXTiledMapLoader();
                    map = mapLoader.loadFromAsset("map01.tmx", MainActivity.this);
                } catch (TMXException e) {
                    Debug.e(e.getMessage());
                }
        //        return null;
        //    }

        //    @Override
        //    protected void onPostExecute(TMXTiledMap tmxTiledMap) {
        //        map = tmxTiledMap;
                if (map != null && (mapLayers = map.getLayers()) != null) {
                    for (TMXLayer layer : mapLayers) {
                        // Determine scene size of the layer.
                        // This enables layer to skip drawing the tile which is out of the screen.
                        layer.setSceneSize(getWidth(), getHeight());

                        // if ground scrolls, child sprite follows it.
                        if ("Ground".equals(layer.getName())) {
                        //    layer.addChild(sprite);
                            scene.getTopLayer().add(layer);
                        }

                        // "Collision" layer is not to be added to the scene
                        // because this layer is just defining collision of the tiles.
                        if ("Collision".equals(layer.getName())) {
                            collisionLayer = layer;
                            continue;
                        }

                        //scene.getTopLayer().remove(loadingText);

                        // Add sprite to the scene.

                        //scene.getTopLayer().add(sprite);
                        //scene.addHUD(controller);

                        // restore refresh rate to default
                        engine.setRefreshMode(E3Engine.REFRESH_DEFAULT);
                    }
                } else {
                    //loadingText.setText("Failed to load!");
                    //loadingText.setAlpha(1);
                    //loadingText.clearModifier();
                }
        //    }
        //}.execute();
        mapX = 0;
        mapY = 0;

        return scene;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onLoadResources() {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onUpdateScene(E3Scene e3Scene, long elapsedMs) {
        for (TMXLayer layer : map.getLayers()) {
            layer.setPosition(mapX, mapY);
        }
    }

    @Override
    public boolean onSceneTouchEvent(E3Scene scene, MotionEvent motionEvent) {
        if (map != null) {
            int action = motionEvent.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    lastTouchX = getTouchEventX(scene, motionEvent);
                    lastTouchY = getTouchEventY(scene, motionEvent);
                    break;
                case MotionEvent.ACTION_MOVE:
                    int x = getTouchEventX(scene, motionEvent);
                    int y = getTouchEventY(scene, motionEvent);
                    int dx = x - lastTouchX;
                    int dy = y - lastTouchY;
                    lastTouchX = x;
                    lastTouchY = y;

                    mapX -= dx;
                    mapY -= dy;
                    if (mapX < 0) mapX = 0;
                    if (mapY < 0) mapY = 0;
                    int maxX = map.getColumns() * map.getTileWidth();
                    int maxY = map.getRows() * map.getTileHeight();
                    if (mapX > maxX) mapX = maxX;
                    if (mapY > maxY) mapY = maxY;
                    break;
            }
        }
        return false;
    }
}
